/* Copyright 2008. All rights reserved. */
package org.bling.process;

import java.lang.reflect.Method;

import org.bling.util.Util;

/**
 * @author DISBROB
 * 
 */
public class Request {

	protected String path;
	protected Class klass;
	protected Method method;
	protected Boolean modal;

	public Request(String path) throws BlingProcessingException {
		this.path = path;
		this.modal = false;

		parsePath(path);

	}
	
	public Request(String path, Boolean modal) throws BlingProcessingException {
		this(path);
		this.modal = true;
	}

	/**
	 * @param path
	 * @throws BlingProcessingException 
	 */
	private void parsePath(String path) throws BlingProcessingException {
		String[] tokens = path.split("/");
		if (tokens.length != 2) {
			throw new BlingProcessingException(
					"requests may only be of format 'controller/method'.  Invalid path: '"
							+ path + "'");
		}

		// Parse Controller
		String controllerTokenString = tokens[0];
		parseController(controllerTokenString);

		// Parse Method
		String methodTokenString = tokens[1];
		parseMethod(controllerTokenString, methodTokenString);

	}

	/**
	 * @param controllerTokenString
	 * @param methodTokenString
	 * @throws BlingProcessingException 
	 */
	private void parseMethod(String controllerTokenString,
			String methodTokenString) throws BlingProcessingException {
		try {
			method = klass.getMethod(methodTokenString);
		} catch (SecurityException e) {
			throw new BlingProcessingException("Can not execute method "
					+ methodTokenString + " on controller "
					+ controllerTokenString);
		} catch (NoSuchMethodException e) {
			throw new BlingProcessingException("No Such Method " + methodTokenString
					+ " on controller " + controllerTokenString);
		}
	}

	/**
	 * @param controllerTokenString
	 * @throws BlingProcessingException 
	 */
	private void parseController(String controllerTokenString) throws BlingProcessingException {
		String name = Util.capitalize(controllerTokenString) + "Controller";
		try {
			klass = Class.forName(name);
		} catch (ClassNotFoundException e) {
			throw new BlingProcessingException("Could not find controller class "
					+ name);
		}
	}

	/**
	 * @return the path
	 */
	public String getPath() {
		return path;
	}

	/**
	 * @param path
	 *            the path to set
	 */
	public void setPath(String path) {
		this.path = path;
	}

	public Class getController() {
		return klass;
	}

	public Method getMethod() {
		return method;
	}

	public String toString() {
		return path;
	}
	
	public Boolean isModal() {
		return modal;
	}
}
